import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;


public class RequestHandler extends Thread{
	
	final int BLOCSIZE = 1024;
	
	Socket server;
	OutputStream os;
	BufferedReader in;
	
	public RequestHandler(Socket server){
		this.server = server;
		
		
		try {
			// we link the stream output to a PrintWriter
			// we link the stream input to a buffered reader
			in = new BufferedReader(new InputStreamReader(this.server.getInputStream()));
			os = server.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		System.out.println("fk yeah le handler rock!");

		String replyCode;
		String inputLine;
		String file = null;
		String httpVersion = null;
		String connection = null;
		System.out.println("\n**** REQUEST HEADER ****");
		//we print the HTTP request
		try {
			while ((inputLine = in.readLine()) != null ) {   
			    System.out.println("Request: " + inputLine);
			    if (inputLine.contains("GET")){
			    	file = inputLine.split(" ")[1];
			    	httpVersion = inputLine.split(" ")[2];
			    }
			    if (inputLine.contains("Connection"))
			    	connection = inputLine.split(" ")[1];
			    if (inputLine.equals(""))
			    	break;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// for debugging purpose
		System.out.println("\nFile: " + file);
		System.out.println("Connection: " + connection);
		System.out.println("HTTP Version: " + httpVersion);
		
		file = file.substring(1);
		
		File myFile = new File(file);
		int fileLength = (int)myFile.length();
		
		if (fileLength != 0){
			replyCode = "200 OK";
		}
		else
			replyCode = "404 Not Found";
		// we send the reply header
		System.out.println("\n**** REPLY HEADER ****");
		writeHeaderLine(httpVersion + " " + replyCode);
		writeHeaderLine("Server: 1337 Server inc.");
		writeHeaderLine("Content-Length: " + fileLength);
		//writeHeaderLine("Content-Type: " + file.substring(file.length()-3));
		writeHeaderLine("Content-Type: " + "text/html");
		writeHeaderLine("\r\n");
		
		// we send the data
		if (replyCode == "200 OK"){
			try {
				int bytesLeft = fileLength;
				byte[] byteArray;
				FileInputStream fis = new FileInputStream(myFile);
				int blockNB = 0;
				while(bytesLeft > 0){
					if(bytesLeft >= BLOCSIZE)
						byteArray = new byte[BLOCSIZE];
					else
						byteArray = new byte[bytesLeft];
					
					
					int byteread = fis.read(byteArray);
					os.write(byteArray);
					os.flush();
					blockNB++;
					bytesLeft -= byteArray.length;
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try {
			os.close();
			in.close();
			server.close();
			
			System.out.println("Request handled and socket closed properly");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
    }
	
	private void writeHeaderLine(String s){
		s = s + "\r\n";
		try {
			os.write(s.getBytes());
			System.out.print("Reply: " + s) ;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
